# -*- coding: utf8 -*-

import os, sys
from pywow.proxy import RealmServerFactory, ProxyServerProtocol, ProxyServerFactory
from twisted.internet import reactor
from pywow.opcodes import opcodes
from pywow.constants import *
from pywow.eggrevenger.plugmgr import pluginManager
from twisted.python.log import startLogging

startLogging(sys.stdout)

class WoWHelperProtocol(ProxyServerProtocol):
 cmd_prefix = '-'
 access = 100
 def handleClientPacket(self, opcode, body):
  print "[Client] %s (%s bytes)" % (opcodes[opcode], len(body))
  self.sendToServer(opcode, body)
 def handleServerPacket(self, opcode, body):
  print "[Server] %s (%s bytes)" % (opcodes[opcode], len(body))
  self.sendToClient(opcode, body)
 def secondConnectionEstablished(self, *args, **kwargs):
  ProxyServerProtocol.secondConnectionEstablished(self, *args, **kwargs)
  self.factory.plugmgr.connected()
 def connectionLost(self, *args, **kwargs):
  ProxyServerProtocol.connectionLost(self, *args, **kwargs)
  self.factory.plugmgr.disconnected()

class WoWHelperFactory(ProxyServerFactory):
 protocol = WoWHelperProtocol
 plugins = None
 pluginManager = pluginManager
 shutting_down = False
 def __init__(self, *args, **kwargs):
  self.config = config
  self.packetHandlers = []
  self.plugmgr = pluginManager(self)
  self.plugmgr.restore()
  reactor.addSystemEventTrigger('before', 'shutdown', self.beforeShutdown)
  ProxyServerFactory.__init__(self, *args, **kwargs)
 def addPacketHandler(self, source, opcode, handler):
  """source can be CLIENT, SERVER or ANY;
  opcode can be $opcode, or ANY
  handler is a function
  it will be called as handler(session, source, opcode, body)
  if it returns True - packet will be proxied,
  if False - dropped.
  """
  self.packetHandlers.append((source, opcode, handler))
 def removePacketHandler(self, source, opcode, handler):
  """params must be the same, as was in addPacketHandler() call
  """
  self.packetHandlers.remove((source, opcode, handler))
 def beforeShutdown(self):
  self.shutting_down = True
  self.plugmgr.unloadAll()

sys.path.insert(0, os.path.expanduser('~/.wowhelper'))
import config
sys.path.pop(0)
sys.path.insert(0, config.core_dir)

bot = WoWHelperFactory(config.destserver, passwd=config.passwd, port=config.proxyport, connectPort=config.destport)
realmd = RealmServerFactory(config.passwd)
realmd.addRealm(bot)

reactor.listenTCP(3724, realmd)
reactor.listenTCP(config.proxyport, bot)

reactor.run()

